import { dialog, IpcMainEvent } from 'electron';
import SerializationService from '../service/SerializationService';
import IpcMainInvokeEvent = Electron.IpcMainInvokeEvent;

class SerializationController {
  async saveJSON(event: IpcMainInvokeEvent, data: object) {
    const { filePath, canceled } = await dialog.showSaveDialog({
      title: '保存 JSON 文件',
      defaultPath: 'workspace.json',
      filters: [{ name: 'JSON Files', extensions: ['json'] }],
    });

    if (canceled || !filePath) {
      return { success: false, error: '用户取消保存' };
    }

    try {
      SerializationService.saveJSONToFile(filePath, data);
      return { success: true };
    } catch (error) {
      return { success: false, error: (error as Error).message };
    }
  }

  async loadJSON(event: IpcMainInvokeEvent) {
    const { canceled, filePaths } = await dialog.showOpenDialog({
      title: '导入 JSON 文件',
      filters: [{ name: 'JSON Files', extensions: ['json'] }],
      properties: ['openFile'],
    });

    if (canceled || filePaths.length === 0) {
      return { success: false, error: '用户取消导入' };
    }

    try {
      const data = SerializationService.loadJSONFromFile(filePaths[0]);
      return { success: true, data };
    } catch (error) {
      return { success: false, error: (error as Error).message };
    }
  }
}

export default new SerializationController();
